package com.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.book.model.entity.Address;
import com.book.mapper.AddressMapper;
import com.book.service.AddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 地址信息 服务实现类
 * </p>
 *
 * @author auto
 * @since 2025-04-02 06:38:55
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Override
    public List<Address> getAddressListByUserId(String userId) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(userId),Address::getUserId, userId);
        return this.list(queryWrapper);
    }

    @Override
    public boolean saveAddress(Address address) {
        if(StringUtils.isNotBlank(address.getAddressId())){
            address.setCreateTime(new Date());
        }
        if(address.getIsDefault() == 1){
            LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Address::getUserId, address.getUserId());
            queryWrapper.eq(Address::getIsDefault, 1);
            List<Address> addressList = this.list(queryWrapper);
            if(CollectionUtils.isNotEmpty(addressList)){
                addressList.forEach(address1 -> {
                    address1.setIsDefault(0);
                });
                this.updateBatchById(addressList);
            }
        }
        return this.saveOrUpdate(address);
    }

    @Override
    public boolean updateAddress(Address address) {
        return this.updateById(address);
    }
}
